import base64
import hashlib
import hmac
import json
import time

import websocket

# Bitget API information for V2
API_KEY = 'bg_fc12ad857c804f07976b30aca52078a3'
SECRET_KEY = '853ea3c8b8e3134dd9d1ee1978b4701e038e8e761f68d11430edd79fb92a9289'
PASSPHRASE = 'LY565900ly'
URL = "wss://ws.bitget.com/v2/ws/private"  # Bitget V2 WebSocket URL


# Function to get current timestamp
def get_timestamp():
    return str(int(time.time() * 1000))


# Generate WebSocket authentication signature (HMAC SHA256)
def generate_signature(secret_key, timestamp):
    message = timestamp + 'GET' + '/user/verify'  # For V2 API: HTTP Method + Path (for WebSocket login, path is /user/stream)
    signature = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).digest()
    return base64.b64encode(signature).decode()


# WebSocket message handler
def on_message(ws, message):
    print("Received message:", message)


# WebSocket connection opened handler
def on_open(ws):
    print("WebSocket connection opened")

    # Step 1: Get current timestamp
    timestamp = get_timestamp()

    # Step 2: Generate signature for WebSocket V2 authentication
    signature = generate_signature(SECRET_KEY, timestamp)

    # Step 3: Send authentication message
    auth_payload = {
        "op": "login",
        "args": [
            {
                "apiKey": API_KEY,
                "passphrase": PASSPHRASE,
                "timestamp": timestamp,
                "sign": signature
            }
        ]
    }

    ws.send(json.dumps(auth_payload))
    print("Sent authentication request")
    time.sleep(3)
    # Step 4: Subscribe to contract account channel (you can change to the appropriate channel)
    subscribe_payload = {
        "op": "subscribe",
        "args": [
            {
                "instType": "USDT-FUTURES",
                "channel": "account",
                "coin": "default"
            }
        ]
    }
    ws.send(json.dumps(subscribe_payload))
    print("Subscribed to contract account channel")


# WebSocket error handler
def on_error(ws, error):
    print("Error occurred:", error)


# WebSocket close handler
def on_close(ws, close_status_code, close_msg):
    print("WebSocket connection closed:", close_status_code, close_msg)


# WebSocket client setup
if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        URL,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close,
        on_open=on_open
    )

    # Start WebSocket connection
    ws.run_forever()
